/**
 * EventBus 组件间传参 by JervisCen 
 * 2018-6-12
 * 
 * 调用方式 
 * 
 *  app.EventBus.$on(name,self,callback)  监听方法，使用时将方法挂载在页面的onLoad周期
 *  app.EventBus.$emit(name,data)  广播方法，
 *  app.EventBus.$remove(name,self) 移除指定监听事件
 *  app.EventBus.$removeAll() 清空events对象
 * 
 *  TODO: 后期改写成公共类
 */

var events = {}; //全局事件对象

//监听事件 name-事件名 self-当前作用域 callback 回调
function on(name, self, callback) {
    var tuple = [self, callback];
    var callbacks = events[name];
    if (Array.isArray(callbacks)) {
        callbacks.push(tuple);
    }else {
        events[name] = [tuple];
    }
}
//移除监听事件 name-事件名 self-当前作用域
function remove(name, self) {
    var callbacks = events[name];
    if (Array.isArray(callbacks)) {
        events[name] = callbacks.filter((tuple) => {
            return tuple[0] != self;
        })
    }
}
//移除当前所有监听事件
function removeAll() {
    events = {};
}

//触发事件方法 name-事件名 data- 参数
function emit(name, data) {
    var callbacks = events[name];
    if (Array.isArray(callbacks)) {
        callbacks.map((tuple) => {
            var self = tuple[0];
            var callback = tuple[1];
            callback.call(self, data);
        })
    }
}

exports.$on = on;
exports.$remove = remove;
exports.$emit = emit;
exports.$removeAll = removeAll;
